package com.niannian.adapter;

import java.util.ArrayList;
import com.niannian.R;
import com.niannian.activity.FamilyMemberDetailActivity;
import com.niannian.activity.FamilyNewsActivity;
import com.niannian.activity.MyInfoEditActivity;
import com.niannian.activity.PushCommentActivity;
import com.niannian.bean.FNCommentBean;
import com.niannian.bean.FamilyNewsBean;
import com.niannian.bean.MyFamilyMemberBean;
import com.niannian.db.MyDBUser;
import com.niannian.dialog.SimpleListDialog;
import com.niannian.dialog.SimpleListDialog.onSimpleListItemClickListener;
import com.niannian.util.Common;
import com.niannian.util.MyLinkMovementMethod;
import com.niannian.util.PlayerManager;
import com.niannian.util.UserInfoManager;
import com.niannian.util.VAR;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 家庭动态评论adapter
 * 
 * @author shenglin
 * 
 */
public class FamilyNewsCommentAdapter extends BaseAdapter {
	protected MyDBUser userInfoManager = UserInfoManager.getUserInfoInstance();
	private ArrayList<FNCommentBean> fComment;
	private LayoutInflater inflater;
	private Activity mActivity;

	private Handler handler;
	FamilyNewsBean fdata;

	private String[] item = { "复制", "删除" };
	private String[] item2 = { "复制" };
	private String[] item3 = { "删除" };
	BaseAdapter adapter;

	public FamilyNewsCommentAdapter(Activity activity, Handler handler, FamilyNewsBean fdata) {
		super();
		this.mActivity = activity;
		this.handler = handler;
		this.fdata = fdata;
		inflater = LayoutInflater.from(mActivity);
		this.fComment = new ArrayList<FNCommentBean>();
		if (!Common.empty(fdata.getCommentBeans())) {
			this.fComment.addAll(fdata.getCommentBeans());
		}
	}

	@Override
	public int getCount() {
		return fComment.size();
	}

	@Override
	public Object getItem(int arg0) {
		return fComment.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	public ArrayList<FNCommentBean> getFDatasList() {
		return fComment;
	}

	public void setAdapter(BaseAdapter adapter) {
		this.adapter = adapter;
	}

	View curView;
	AnimationDrawable ad;

	@Override
	public View getView(final int position, View view, ViewGroup arg2) {
		ViewHolder holder = null;
		if (view == null) {
			view = inflater.inflate(R.layout.family_news_comment_item, null);
			holder = new ViewHolder();
			holder.ll_fn_comment_item = (LinearLayout) view.findViewById(R.id.ll_fn_comment_item);
			holder.tv_fn_comment_name = (TextView) view.findViewById(R.id.tv_fn_comment_name);
			holder.tv_fn_comment_info = (TextView) view.findViewById(R.id.tv_fn_comment_info);

			holder.tv_aud_len = (TextView) view.findViewById(R.id.tv_aud_len);
			holder.btn_play = (RelativeLayout) view.findViewById(R.id.btn_play);
			holder.iv_status_play = (ImageView) view.findViewById(R.id.iv_status_play);

			holder.tv_fn_comment_name.setVisibility(View.GONE);
			holder.pb_fn_loading = (ProgressBar) view.findViewById(R.id.pb_fn_loading);
			view.setTag(holder);
		} else {
			holder = (ViewHolder) view.getTag();
		}
		final FNCommentBean cdata = fComment.get(position);

		if (!Common.empty(cdata.getAud())) {
			holder.btn_play.setVisibility(View.VISIBLE);
			holder.tv_aud_len.setText(Common.showAudLen(cdata.getAud_len()));

			// 播放视图显示
			if (PlayerManager.getAudioPlayer(mActivity).currPlayingPath.equals(cdata.getAud())) {

				if (PlayerManager.getAudioPlayer(mActivity).isPlayStatus == 1) {


					holder.iv_status_play.setBackgroundResource(R.anim.family_status_play_comment_anim);
					ad = (AnimationDrawable) holder.iv_status_play.getBackground();
					holder.iv_status_play.getViewTreeObserver().addOnPreDrawListener(opdl);

				} else if (PlayerManager.getAudioPlayer(mActivity).isPlayStatus == 2) {
					holder.iv_status_play.setBackgroundResource(R.drawable.status_pause_comment);
				} else {
					holder.iv_status_play.setBackgroundResource(R.drawable.play_comment_3);
				}
			} else {
				holder.iv_status_play.setBackgroundResource(R.drawable.play_comment_3);
			}

		} else {
			holder.btn_play.setVisibility(View.GONE);
		}

		if (PlayerManager.getAudioPlayer(mActivity).DownloadingMap.containsKey(cdata.getAud())) {
			holder.pb_fn_loading.setVisibility(View.VISIBLE);
		} else {
			holder.pb_fn_loading.setVisibility(View.GONE);
		}
		String info = "";
		String aname = "";
		String isReplyName = "";
		String isReplyToName = "";
		if (cdata.getReply_to() > 0) {
			if (cdata.getAuthor_nickname().length() > 5) {
				isReplyName = cdata.getAuthor_nickname().substring(0, 5) + "..";
			} else {
				isReplyName = cdata.getAuthor_nickname();
			}
			if (cdata.getReply_to_nickname().length() > 5) {
				isReplyToName = cdata.getReply_to_nickname().substring(0, 5) + "..";
			} else {
				isReplyToName = cdata.getReply_to_nickname();
			}
			info = isReplyName + "回复" + isReplyToName + ": " + cdata.getInfo();
		} else {
			if (cdata.getAuthor_nickname().length() > 5) {
				aname = cdata.getAuthor_nickname().substring(0, 5) + "..";
			} else {
				aname = cdata.getAuthor_nickname();
			}
			info = aname + ": " + cdata.getInfo();
		}

		SpannableString spannableString = new SpannableString(info);

		if (cdata.getReply_to() > 0) {
			spannableString.setSpan(new tagClickSpan(cdata.getAuthor(), cdata.getAuthor_nickname()), 0, isReplyName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			spannableString.setSpan(new tagClickSpan(cdata.getReply_to(), cdata.getReply_to_nickname()), isReplyName.length() + 2, isReplyName.length() + 2
					+ isReplyToName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		} else {
			spannableString.setSpan(new tagClickSpan(cdata.getAuthor(), cdata.getAuthor_nickname()), 0, aname.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		}

		holder.tv_fn_comment_info.setMovementMethod(new MyLinkMovementMethod(holder.ll_fn_comment_item));
		holder.tv_fn_comment_info.setText(spannableString);

		holder.btn_play.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (System.currentTimeMillis() - VAR.ExitTime > VAR.INTERVAL) {
					PlayerManager.getAudioPlayer(mActivity).aPlayer(adapter, cdata.getAud());

					VAR.ExitTime = System.currentTimeMillis();
				}
			}
		});

		holder.ll_fn_comment_item.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (System.currentTimeMillis() - VAR.ExitTime > VAR.INTERVAL) {
					if (userInfoManager.id == cdata.getAuthor()) {
						curView = v;
						initChooseDialog(cdata, position);
					} else {
						Intent intent = new Intent(mActivity, PushCommentActivity.class);
						intent.putExtra("fid", fdata.getId());
						intent.putExtra("reply_to", cdata.getAuthor());
						intent.putExtra("reply_to_nickname", cdata.getAuthor_nickname());
						mActivity.startActivityForResult(intent, FamilyNewsActivity.PUSH_COMMENT);
						VAR.ExitTime = System.currentTimeMillis();
					}
				}
			}
		});
		holder.ll_fn_comment_item.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				curView = v;
				initChooseDialog(cdata, position);
				return true;
			}
		});

		if (cdata.getIsdelete() == 1) {
			removeListItem(view, position);
		}

		return view;
	}

	SimpleListDialog listDialog;

	private void initChooseDialog(final FNCommentBean fdata, final int listPostion) {
		listDialog = new SimpleListDialog(mActivity);
		if (userInfoManager.id == fdata.getAuthor()) {
			if (fdata.getInfo().length() > 0) {
				listDialog.setAdapter(new ListDialogAdapter(mActivity, item));
			} else {
				listDialog.setAdapter(new ListDialogAdapter(mActivity, item3));
			}

		} else {
			if (fdata.getInfo().length() > 0) {
				listDialog.setAdapter(new ListDialogAdapter(mActivity, item2));
			} else {
				return;
			}
		}
		listDialog.serOnSimpleListItemClikListener(new onSimpleListItemClickListener() {
			@Override
			public void onItemClick(int postion) {

				listDialog.dismiss();

				switch (postion) {
				case 0:
					if (fdata.getInfo().length() > 0) {
						Common.copy(fdata.getInfo(), mActivity);
					} else {
						DeleteCommentDialog(fdata.getId(), listPostion);
					}
					break;
				case 1:
					DeleteCommentDialog(fdata.getId(), listPostion);
					break;

				}
			}
		});
		listDialog.show();
	}

	// 删除动态提示
	// YesNoDialog2 tip;

	private void DeleteCommentDialog(final int cid, final int position) {
		// tip = new YesNoDialog2(mActivity, "确认要删除吗?");
		// tip.setOnCancelListener(new onSimpleOnCancelListener() {
		//
		// @Override
		// public void onCancel() {
		// tip.dismiss();
		// }
		// });
		// tip.setOnConfimClickListener(new onSimpleOnClicklListener() {
		//
		// @Override
		// public void onClick() {
		//
		// tip.dismiss();
		// removeListItem(curView, cid, position);
		// }
		// });
		// tip.show();

		Message msg = new Message();
		msg.what = FamilyNewsActivity.DELETE_NEWS_COMMENT;
		msg.arg1 = fdata.getId();
		msg.arg2 = cid;
		handler.sendMessage(msg);

	}

	protected void removeListItem(View rowView, final int positon) {
		//
		// try {
		// //fComment.remove(positon);
		// fdata.getCommentBeans().remove(positon);
		//
		// handler.sendEmptyMessage(FamilyNewsActivity.DELETE_NEWS_COMMENT_ANIM);
		// } catch (Exception e) {
		// // TODO: handle exception
		// handler.sendEmptyMessage(FamilyNewsActivity.DELETE_NEWS_COMMENT_ANIM);
		// }

		// final Animation animation = (Animation)
		// AnimationUtils.loadAnimation(rowView.getContext(), R.anim.item_anim);
		// animation.setAnimationListener(new AnimationListener() {
		// public void onAnimationStart(Animation animation) {
		// }
		//
		// public void onAnimationRepeat(Animation animation) {
		// }
		//
		// public void onAnimationEnd(Animation animation) {
		// try {
		// fComment.remove(positon);
		// fdata.getCommentBeans().remove(positon);
		// notifyDataSetChanged();
		// animation.cancel();
		// handler.sendEmptyMessage(FamilyNewsActivity.DELETE_NEWS_COMMENT_ANIM);
		// } catch (Exception e) {
		// // TODO: handle exception
		// handler.sendEmptyMessage(FamilyNewsActivity.DELETE_NEWS_COMMENT_ANIM);
		// }
		//
		// }
		// });
		//
		// rowView.startAnimation(animation);
	}

	class ViewHolder {
		LinearLayout ll_fn_comment_item;
		TextView tv_fn_comment_name;

		TextView tv_fn_comment_info;

		ProgressBar pb_fn_loading;

		TextView tv_aud_len;
		RelativeLayout btn_play;
		ImageView iv_status_play;
	}

	OnPreDrawListener opdl = new OnPreDrawListener() {
		@Override
		public boolean onPreDraw() {
			ad.start();
			return true; 
		}
	};

	class tagClickSpan extends ClickableSpan {
		int id = 0;
		String name = "";

		public tagClickSpan(int id, String name) {
			this.id = id;
			this.name = name;
		}

		@Override
		public void onClick(View widget) {
			if (widget instanceof TextView) {
				try {

					if (userInfoManager.id == id) {
						Intent intent = new Intent(mActivity, MyInfoEditActivity.class);
						mActivity.startActivity(intent);
						mActivity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
					} else {
						MyFamilyMemberBean fd = new MyFamilyMemberBean();
						fd.setId(id);
						fd.setNickname(name);
						Intent intent = new Intent(mActivity, FamilyMemberDetailActivity.class);
						intent.putExtra("data", fd);
						mActivity.startActivity(intent);
						mActivity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
					}

				} catch (Exception e) {
					// TODO: handle exception
				}

			}
		}

		public void updateDrawState(TextPaint ds) {
			super.updateDrawState(ds);
			// 设置没有下划线
			ds.setUnderlineText(false);
			// 设置颜色高亮
			ds.setColor(0xff076BAE);
		}
	}

}
